package com.northpool.operator.http.covert;

import cn.hutool.core.io.IoUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.algorithm.AlgorithmBase;
import com.northpool.operator.common.minio.MinIOUtil;
import com.northpool.operator.type.TypeEnum;
import io.minio.Result;
import io.minio.messages.Item;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@OperatorInfo(
        ref = "XMLPrettyOperator",
        name = "XML格式美化",
        description = "扫描对象存储中的文件，XML格式美化"
)
public class XMLPrettyOperator extends AlgorithmBase {

    @InputParams({
            @InputParam(ref = "path", name = "minio中对象路径", desc = "minio中对象路径, 如: apps/supermap/"),
            @InputParam(ref = "minioEndpoint", name = "对象存储地址", desc = "http://ip:port"),
            @InputParam(ref = "bucket", name = "桶名称", desc = "桶名称, 如: stp-minio"),
            @InputParam(ref = "accessKey", name = "minio令牌", desc = "minio令牌", type = TypeEnum.SECRET),
            @InputParam(ref = "secretKey", name = "minio密钥", desc = "minio密钥", type = TypeEnum.SECRET)
    })
    public XMLPrettyOperator() {

    }

    public static void main(String[] args) throws Exception {
        String bucket = "stp-minio";
        String path = "apps/supermap/";
        String minioEndpoint = "http://northpool.work:9000";
        String accessKey = "northpool";
        String secretKey = "piesat@123";

        MinIOUtil minioUtil = new MinIOUtil(minioEndpoint, accessKey, secretKey);
        XMLPrettyOperator xmlPrettyOperator = new XMLPrettyOperator();

        xmlPrettyOperator.processDirItem(minioUtil, bucket, path);
    }

    @Override
    public void execute(Map<String, String> params) {
        String bucket = params.get("bucket");
        String path = params.get("path");
        String minioEndpoint = params.get("minioEndpoint");
        String accessKey = params.get("accessKey");
        String secretKey = params.get("secretKey");

        MinIOUtil minioUtil = new MinIOUtil(minioEndpoint, accessKey, secretKey);
        try {
            processDirItem(minioUtil, bucket, path);
        } catch (Exception ex) {
            logError("处理失败" + ex.getMessage());
            failedExit();
        }
    }

    private void processDirItem(MinIOUtil minioUtil, String bucket, String path) throws Exception {
        Iterable<Result<Item>> results = minioUtil.listObjects(bucket, path);
        for (Result<Item> result : results) {
            Item item = result.get();
            boolean dir = item.isDir();
            if (dir) {
                processDirItem(minioUtil, bucket, item.objectName());
            } else {
                try {
                    processFileIte(minioUtil, bucket, item.objectName());
                } catch (Exception ex) {
                    logInfo("文件格式化处理失败：" + item.objectName());
                }

            }
        }
    }

    private void processFileIte(MinIOUtil minioUtil, String bucket, String objectName) throws Exception {
        if (!objectName.endsWith(".xml")) {
            return;
        }
        InputStream inputStream = minioUtil.getObject(bucket, objectName);
        String xmlString = IoUtil.readUtf8(inputStream);

        Document document = DocumentHelper.parseText(xmlString);

        // 创建 OutputFormat 对象并设置美化输出
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8"); // 设置编码

        // 使用 StringWriter 来捕获输出
        StringWriter out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, format);

        // 写入文档
        writer.write(document);
        writer.close();

        // 删除原有的xml文件
        minioUtil.removeObject(bucket, objectName);

        // 新增格式化后的xml文件
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8));
        minioUtil.putObject(bucket, objectName, byteArrayInputStream, "text/xml; charset=utf-8");
        logInfo("处理完成：" + objectName);
    }
}
